import axios from 'axios'
import io from "socket.io-client";
const socket = io("ws://localhost:9093");

const USER_LIST = 'USER_LIST'
const MSG_LIST = 'MSG_LIST'
const MSG_RECV = 'MSG_RECV'
// 表示已读
const MSG_READ = 'MSG_READ'

const initState = {
  userlist: [],
  chatmsg: [],
  users: {},
  unread: 0,
}
// reducer
export function chatuser(state = initState, action) {
  switch (action.type) {
    case USER_LIST:
      return { ...state,
        userlist: action.payload
      }
    case MSG_LIST:
      return { ...state,
        users: action.payload.users,
        chatmsg: action.payload.data,
        unread: action.payload.data.filter(v => !v.read && v.to == action.payload.userid).length
      }
    case MSG_RECV:
      const n = action.payload.to === action.userid ? 1 : 0
      return { ...state,
        chatmsg: [...state.chatmsg, action.payload],
        unread: state.unread + n
      }
    case MSG_READ:
      const {
        from,
        num
      } = action.payload
      return { ...state,
        unread: state.unread - num,
        chatmsg: state.chatmsg.map(v => ({ ...v,
          read: from === v.from ? true : v.read
        }))
      }
    default:
      return state
  }
}


function msgList(data, users, userid) {
  return {
    type: MSG_LIST,
    payload: {
      data,
      users,
      userid
    }
  }
}

function msgRecv(msg, userid) {
  return {
    type: MSG_RECV,
    userid,
    payload: msg
  }
}

function userList(data) {
  return {
    type: USER_LIST,
    payload: data
  }
}

function msgRead({
  from,
  userid,
  num
}) {
  return {
    type: MSG_READ,
    payload: {
      from,
      userid,
      num
    }
  }
}
export function readMsg(from) {
  return async (dispatch, getState) => {
    const res = await axios.post('/user/readmsg', {from})
    const userid = getState().user._id
    if (res.status === 200 && res.data.success) {
      dispatch(msgRead({
        userid,
        from,
        num: res.data.num
      }))
    }
  }
}

export function sendMsg({
  from,
  to,
  msg
}) {
  return dispatch => {
    socket.emit('sendmsg', {
      from,
      to,
      msg
    })
  }
}

export function recvMsg() {
  return (dispatch, getState) => {
    socket.on('recvmsg', function (data) {
      const userid = getState().user._id
      dispatch(msgRecv(data, userid))
    })
  }
}


export function getMsgList() {
  return (dispatch, getState) => {
    axios.get('/user/getmsglist')
      .then(res => {
        if (res.status === 200 && res.data.success) {
          const userid = getState().user._id
          dispatch(msgList(res.data.data, res.data.users, userid))
        }
      })
  }
}


export function getUserList(type) {
  console.log(type)
  return dispatch => {
    axios.get("/user/list?type=" + type).then(res => {
      if (res.data.success) {
        dispatch(userList(res.data.data))
      }
    });
  }
}